// pages/book-detail/book-detail.js
import {
  bookModel
} from '../../models/book.js'
import {
  likeModel
} from '../../models/liek.js'
const bookMode = new bookModel()
const likeMode = new likeModel()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    comments: [],
    book: null,
    likeStatus: false,
    likeCount: 0,
    posting: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading()
    const bid = options.bid
    bookMode.getDetail(bid, (res) => {
      this.setData({
        book: res.data
      })
      // 此时可以使用promise来做并行下载串行显示来提高效率
      wx.hideLoading()
    })
    bookMode.getLikeStatus(bid, (res) => {
      this.setData({
        likeCount: res.data.fav_nums,
        likeStatus: res.data.like_status
      })
    })
    bookMode.getBookComments(bid, (res) => {
      this.setData({
        comments: res.data.comments
      })
    })
  },

  clikLick: function (even) {
    let likeState = even.detail.likeState
    likeMode.like(likeState, this.data.book.id, 400)
  },

  onFakePost: function(){
    this.setData({
      posting: true
    })
  },

  onCancel: function(){
    this.setData({
      posting: false
    })
  },

  onPost: function(even){
    const bid = this.data.book.id
    // const commentTag = even.detail.text
    // const commentTnput = even.detail.value
    // const comment = commentTag || commentTnput

    const comment = even.detail.text || even.detail.value.trim()
  
    if(comment.length > 12) {
      wx.showToast({
        title: '短评最多可输入12个字符',
        icon: 'none',
        mask: true,
        duration: 300
      })
      return
    }
    bookMode.putBookComments(bid,comment,()=>{
      wx.showToast({
        title: '+1',
        icon: 'none',
        mask: true,
        duration: 300
      })
    })
    this.data.comments.unshift({
      content: comment,
      nums: 1
    })
    this.setData({
      comments: this.data.comments,
      posting: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
